<template>
  <div class="notification-container">
    <!-- 通知对话框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      width="30%"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      center
    >
      <div class="notification-content">
        <i :class="['notification-icon', type === 1 ? 'el-icon-bell' : 'el-icon-warning']"></i>
        <span class="notification-text">{{ content }}</span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleClose">我知道了</el-button>
      </span>
    </el-dialog>

    <!-- 音频播放器 -->
    <audio 
      ref="newOrderAudio" 
      src="/audio/reminder.mp3" 
      preload="auto"
      @canplaythrough="handleCanPlayThrough('newOrderAudio')"
    ></audio>
    <audio 
      ref="urgentOrderAudio" 
      src="/audio/preview.mp3" 
      preload="auto"
      @canplaythrough="handleCanPlayThrough('urgentOrderAudio')"
    ></audio>
  </div>
</template>

<script>
// 全局WebSocket实例，避免重复创建
let globalWebSocket = null
let globalSid = null

export default {
  name: 'WebSocketNotification',
  data() {
    return {
      websocket: null,
      dialogVisible: false,
      type: 1, // 1: 新订单提醒, 2: 催单提醒
      content: '',
      orderId: '',
      reconnectTimer: null,
      reconnectCount: 0,
      maxReconnectCount: 5,
      isConnecting: false,
      audioLoaded: {
        newOrderAudio: false,
        urgentOrderAudio: false
      },
      audioContext: null,
      audioBuffers: {}
    }
  },
  created() {
    console.log('WebSocketNotification组件创建')
    this.initWebSocket()
    this.initAudioContext()
  },
  beforeDestroy() {
    console.log('WebSocketNotification组件销毁')
    this.closeWebSocket()
  },
  methods: {
    // 初始化音频上下文
    initAudioContext() {
      try {
        window.AudioContext = window.AudioContext || window.webkitAudioContext
        this.audioContext = new AudioContext()
        
        // 预加载音频文件
        this.preloadAudio('/audio/reminder.mp3', 'newOrderAudio')
        this.preloadAudio('/audio/preview.mp3', 'urgentOrderAudio')
      } catch (error) {
        console.error('初始化音频上下文失败:', error)
      }
    },

    // 预加载音频文件
    async preloadAudio(url, key) {
      try {
        const response = await fetch(url)
        const arrayBuffer = await response.arrayBuffer()
        const audioBuffer = await this.audioContext.decodeAudioData(arrayBuffer)
        this.audioBuffers[key] = audioBuffer
        console.log(`音频文件 ${key} 预加载完成`)
      } catch (error) {
        console.error(`预加载音频文件 ${key} 失败:`, error)
      }
    },

    // 播放音频
    async playAudio(key) {
      try {
        if (this.audioContext.state === 'suspended') {
          await this.audioContext.resume()
        }

        const source = this.audioContext.createBufferSource()
        source.buffer = this.audioBuffers[key]
        source.connect(this.audioContext.destination)
        source.start(0)
      } catch (error) {
        console.error(`播放音频 ${key} 失败:`, error)
      }
    },

    // 处理音频加载完成事件
    handleCanPlayThrough(audioRef) {
      this.audioLoaded[audioRef] = true
      console.log(`${audioRef} 加载完成`)
    },

    // 初始化WebSocket连接
    initWebSocket() {
      // 防止重复连接
      if (this.isConnecting) {
        console.log('WebSocket正在连接中，跳过重复初始化')
        return
      }

      // 如果全局WebSocket已存在且连接正常，直接使用
      if (globalWebSocket && globalWebSocket.readyState === WebSocket.OPEN) {
        console.log('使用现有的WebSocket连接')
        this.websocket = globalWebSocket
        this.bindWebSocketEvents()
        return
      }

      // 如果存在未完全关闭的连接，先关闭它
      if (globalWebSocket && globalWebSocket.readyState !== WebSocket.CLOSED) {
        console.log('关闭之前的WebSocket连接')
        globalWebSocket.close()
        globalWebSocket = null
      }

      this.isConnecting = true

      try {
        // 生成唯一的会话ID
        if (!globalSid) {
          globalSid = 'client_' + Date.now() + '_' + Math.random().toString(36).substring(2)
        }
        
        // 根据当前环境确定WebSocket地址
        const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
        const host = process.env.NODE_ENV === 'development' ? '127.0.0.1:8080' : window.location.host
        const wsUrl = `${protocol}//${host}/ws/${globalSid}`
        
        console.log('正在连接WebSocket:', wsUrl)
        
        globalWebSocket = new WebSocket(wsUrl)
        this.websocket = globalWebSocket
        
        this.bindWebSocketEvents()
        
      } catch (error) {
        console.error('初始化WebSocket失败:', error)
        this.isConnecting = false
      }
    },

    // 绑定WebSocket事件
    bindWebSocketEvents() {
      if (!this.websocket) return

      this.websocket.onopen = (event) => {
        console.log('WebSocket连接已建立', event)
        this.reconnectCount = 0 // 重置重连次数
        this.isConnecting = false
      }
      
      this.websocket.onmessage = (event) => {
        console.log('收到WebSocket消息:', event.data)
        try {
          const data = JSON.parse(event.data)
          this.handleMessage(data)
        } catch (error) {
          console.error('解析WebSocket消息失败:', error)
        }
      }
      
      this.websocket.onerror = (error) => {
        console.error('WebSocket连接错误:', error)
        this.isConnecting = false
      }
      
      this.websocket.onclose = (event) => {
        console.log('WebSocket连接已关闭:', event.code, event.reason)
        this.isConnecting = false
        
        // 清理全局引用
        if (globalWebSocket === this.websocket) {
          globalWebSocket = null
          globalSid = null
        }
        
        this.websocket = null
        
        // 只有在非手动关闭的情况下才重连
        if (event.code !== 1000 && this.reconnectCount < this.maxReconnectCount) {
          this.reconnectCount++
          console.log(`尝试第${this.reconnectCount}次重连...`)
          this.reconnectTimer = setTimeout(() => {
            this.initWebSocket()
          }, 3000)
        }
      }
    },
    
    // 处理接收到的消息
    handleMessage(data) {
      this.type = data.type || 1
      this.content = data.content || '收到新消息'
      this.orderId = data.orderId || ''
      this.dialogVisible = true
      
      // 播放对应的提示音
      this.$nextTick(async () => {
        try {
          if (this.type === 1) {
            await this.playAudio('urgentOrderAudio')
          } else {
            await this.playAudio('newOrderAudio')
          }
        } catch (error) {
          console.log('播放提示音失败:', error)
        }
      })
    },
    
    // 关闭通知对话框
    handleClose() {
      this.dialogVisible = false
      // 如果是催单消息，可以跳转到订单详情页面
      if (this.type === 2 && this.orderId) {
        // 获取当前路由信息
        const currentRoute = this.$route
        const targetPath = `/order?orderId=${this.orderId}`

        // 只有当目标路径与当前路径不同时才进行跳转
        if (currentRoute.fullPath !== targetPath) {
          this.$router.push(targetPath).catch(err => {
            if (err.name !== 'NavigationDuplicated') {
              console.error('路由跳转失败:', err)
            }
          })
        }
      }
    },
    
    // 关闭WebSocket连接
    closeWebSocket() {
      if (this.reconnectTimer) {
        clearTimeout(this.reconnectTimer)
        this.reconnectTimer = null
      }
      
      // 只有当前组件是最后一个使用WebSocket的组件时才关闭连接
      if (this.websocket && this.websocket === globalWebSocket) {
        console.log('关闭WebSocket连接')
        this.websocket.close(1000, '用户主动关闭')
        globalWebSocket = null
        globalSid = null
      }
      
      this.websocket = null
      this.isConnecting = false
    }
  }
}
</script>

<style scoped>
.notification-container {
  position: fixed;
  z-index: 9999;
}

.notification-content {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.notification-icon {
  font-size: 24px;
  margin-right: 10px;
}

.notification-icon.el-icon-bell {
  color: #409EFF;
}

.notification-icon.el-icon-warning {
  color: #E6A23C;
}

.notification-text {
  font-size: 16px;
  color: #333;
}

.dialog-footer {
  text-align: center;
}
</style>